// src/i18n.ts
import i18n, { Resource } from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

// 预加载默认语言
import enTranslations from "./en.json";
import zhTranslations from './zh.json';
import jaTranslations from './ja.json';
import koTranslations from './ko.json';

// 定义资源类型
type TranslationResources = {
  [key: string]: {
    translation: typeof enTranslations
  }
};

const resources: Resource = {
  en: { translation: enTranslations },
  zh: { translation: zhTranslations },
  ja: { translation: jaTranslations },
  ko: { translation: koTranslations }
} as const;

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    react: {
      bindI18n: 'languageChanged',
      bindI18nStore: '',
      useSuspense: false
    },
    fallbackLng: 'en',
    supportedLngs: ['en', 'zh', 'ja', 'ko'],
    detection: {
      order: ['localStorage', 'navigator'],
      caches: ['localStorage'],
      checkWhitelist: true
    },
    interpolation: {
      escapeValue: false
    }
  });

// 动态加载语言类型
type AvailableLocales = 'en' | 'zh' | 'ja' | 'ko';

const loadDynamicLocale = async (lng: string) => {
  const language = lng.split('-')[0] as AvailableLocales;

  if (!i18n.hasResourceBundle(language, 'translation')) {
    try {
      const module = await import(
        /* webpackChunkName: "locale-[request]" */
        `./language/${language}.json`
      );
      i18n.addResourceBundle(language, 'translation', module.default);
    } catch (error) {
      console.warn(`Language ${language} not available`);
      i18n.setFallbackLng('en');
    }
  }
};

i18n.on('languageChanged', (lng: string) => {
  loadDynamicLocale(lng);
});

// 初始化加载
loadDynamicLocale(i18n.language);

export default i18n;